<!-- extends 表明次页面继承自 base.html文件-->
{% extends 'base.html' %}
{% load staticfiles %}
{% load my_filters_and_tags %}
{% show_comments_pub_time article %}


<!-- 写入 base.html 中定义的 title-->
{% block title %} 文章详情 {% endblock title %}

<!-- 写入 base.html 中定义的 content-->
{% block content %}
<!--<script src="{% static 'ckeditor/ckeditor/plugins/prism/plugin.js' %}"></script>-->
<script src="{% static 'ckeditor/ckeditor/plugins/prism/lib/prism/prism_patched.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'prism/prism.css' %}">
    <!-- 文章详情 -->
    <div class="container">
        <div class="row">
             <!-- 将原有内容嵌套进新的div中 -->
            <div class="col-9">
                <!-- 标题及作者-->
                <h1 class="mt-4 mb-4">{{ article.title }}</h1>
                <div class="alert alert-success">作者：{{ article.author }}
                    {% if user == article.author %}
                    • <a href="#" onclick="confirm_safe_delete()">删除文章</a>
                    • <a href="{% url 'article:article_update' article.id %}">编辑文章</a>
                    {% endif %}
                    <div>浏览：{{ article.total_views }}</div>
                    <!-- 新增一个隐藏的表单 -->
                    <form
                        style="display:none;"
                        id="safe_delete"
                        action="{% url 'article:article_safe_delete' article.id %}"
                        method="POST">
                        {% csrf_token %}
                        <button type="submit">发送</button>
                    </form>
                </div>
            </div>
             <!-- 新增的目录 -->
            <div class="col-3 mt-4 sidebar" id="sidebar" name="sidebar">
                <div class="sidebar__inner">
                    <h4><strong>目录</strong></h4>
                    <hr>
                    <div>{{ toc|safe }}</div>
                </div>
            </div>
            <!-- 文章正文 -->
            <div class="col-9">文章内容：
                <div class="alert alert-success" style="height:200px" >
                <!--  在 article.body 后加上 |safe 过滤器,表示这一段字符不需要进行转义-->
                <p>{{ article.body|safe }}</p>
                </div>
            </div>

            <!-- 新增点赞按钮 -->
            <div class="mt-4 col-9 col-auto" style="text-align:right;">
                <button class="btn btn-outline-danger" type="button"
                        onclick="validate_is_like(
                        '{% url 'article:increase_likes' article.id %}',
                        {{ article.id }},
                        {{ article.likes }}
                        )">
                    <span>点赞</span>
                    <span><i class="fas fa-heart"></i></span>
                    <span id="likes_number">{{ article.likes }}</span>
                </button>
            </div>

            <!-- 相邻文章导航 -->
            <div class="row justify-content-end col-9" style="margin-top:3rem;">
                {% if next_article %}
                <div class="col-auto mr-auto">
                    <a  href="{{ next_article.get_absolute_url }}"
                        class="btn btn-info"
                        >
                        {{ next_article.title }}
                    </a>
                </div>
                {% endif %}
            {% if pre_article %}
                <div class="col-auto" style="text-align:right;">
                    <a  href="{{ pre_article.get_absolute_url }}"
                    class="btn btn-info"
                    >
                        {{ pre_article.title }}
                    </a>
                </div>
            {% endif %}
             </div>

            <!-- 发表评论 -->
            <hr>
            {% if user.is_authenticated %}
                    <form action="{% url 'comment:post_comment' article.id %}" method="POST">
                        {% csrf_token %}
                        <div class="form-group" style="margin-top:1rem">
                            <label><strong>我也要发言：</strong></label>
                            <div>
                                {{ comment_form.media }}
                                {{ comment_form.body }}
                            </div>
                        </div>
                        <!-- 提交按钮 -->
                        <button class="btn btn-primary" type="submit">发送</button>
                    </form>
                <br>
            {% else %}
                <br>
                <h5 class="col-9 row justify-content-center"> 请 <a href="{% url 'userprofile:login' %}">登录</a>后回复</h5>
                <br>
            {% endif %}
                </div>

        <!-- 显示评论 -->
            {% load mptt_tags %}
            <div class=" col-9">
                <h4>共有{{ comments.count }}条评论</h4>
                <div class="row"></div>
                    <!-- 遍历树形结构 -->
                    {% recursetree comments %}
                    <!-- 给 node 取个别名 comment -->
                        {% with comment=node %}
                            <div class="
                                {% if comment.reply_to %}
                                offset-1 col-11
                                {% else %}
                                col-12
                                {% endif %}" id="comment_elem_{{ comment.id }}">
                                <hr>
                                <p><strong style="color: pink">{{ comment.user }}</strong>
                                    {% if comment.reply_to %}
                                        <i class="far fa-arrow-alt-circle-right" style="color: cornflowerblue;"></i>
                                        <strong style="color: pink">{{ comment.reply_to }}</strong>
                                    {% endif %}
                                </p>
                                <div>{{ comment.body|safe }}</div>

                                <div>
                                    <span style="color: gray">{{ comment.created|date:'Y-m-d H:i' }}</span>
                                    <!-- 加载 modal 的按钮 -->
                                    {% if user.is_authenticated %}
                                        <button class="btn btn-light btn-sm text-muted" type="button"
                                                onclick="load_modal({{ article.id }}, {{ comment.id }})">
                                            回复
                                        </button>
                                    {% else %}
                                        <a href="{% url 'userprofile:login' %}"
                                           class="btn btn-light btn-sm text-muted">回复
                                        </a>
                                    {% endif %}
                                </div>

                                <!-- Modal -->
                                <div class="modal fade" id="comment_{ comment.id }" tabindex="-1"
                                     role="dialog" aria-labelledby="CommentModalCenter" aria-hidden="true">
                                    <div class="modal-dialong modal-dialog-centered modal-lg" role="document">
                                        <div class="modal-content" style="height:480px">
                                            <div class="modal-header">
                                                <h5 class="modal-title" id="exampleModalCenterTitle">
                                                    回复{{ comment.user }}</h5>
                                            </div>
                                            <div class="modal-body" id="modal_body_{{ comment.id }}"></div>
                                        </div>
                                    </div>
                                </div>
                                {% if not comment.is_leaf_node %}
                                    <div class="children">{{ children }}</div>
                                {% endif %}
                             </div>
                        {% endwith %}
                    {% endrecursetree %}

            </div>
            </div>
        </div>


<!-- 粘性侧边栏样式 -->
<style>
    .sidebar{
        will-change: min-height;
    }

    .sidebar__inner{
        transform: translate(0, 0); /* For browsers don't support translate3d. */
        transform: translate3d(0, 0, 0);
        will-change: position, transform;
    }
</style>


<script>
    // 刪除文章的函數
    function confirm_safe_delete(){
        // 调用layer弹窗組件
        layer.open({
            // 弹窗标题
            title: '确认刪除',
            // 正文
            content: '确认删除这篇文章吗？',
            // 点击确定按钮后调用的回调函数
            yes: function(index, layero){
                $('form#safe_delete button').click();
                layer.close(index)
            },
        })
    }
</script>
{% endblock content %}

{% block script %}
<!-- csrf token -->
<script src="{% static 'csrf.js' %}"></script>

<script>
 // 加载 modal
    function load_modal(article_id, comment_id) {
        let modal_body = '#modal_body_' + comment_id;
        let modal_id = '#comment_' + comment_id;

        // 加载编辑器
        if ($(modal_body).children().length === 0) {
            let content = '<iframe src="/comment/post-comment/' +
                article_id +
                '/' +
                comment_id +
                '"' +
                'frameborder="0" style="width: 100%; height: 100%;" id="iframe_' +
                comment_id +
                '"></iframe>';
            $(modal_body).append(content);
            console.log(content)
        };
        $(modal_id).modal('show');
    }
</script>

    <!-- 引入粘性侧边栏 -->
<script>
    $('#sidebar').stickySidebar({
        topSpacing: 20,
        bottomSpacing: 20
    });
</script>

<!-- Ckeditor自适应 -->
<script>
    $(".django-ckeditor-widget").removeAttr('style');
</script>

<script>
     // 处理二级回复
     function post_reply_and_show_it(new_comment_id){
        let next_url = "{% url 'article:article_detail' article.id %}";
        // 去除 url 尾部 '/' 符号
        next_url = next_url.charAt(next_url.length - 1) == '/' ? next_url.slice(0, -1) : next_url;
        // 刷新并定位到锚点
        window.location.replace(next_url + "#comment_elem_" + new_comment_id);
     };
</script>

<script>
 // 点赞功能主函数
    function validate_is_like(url, id, likes) {
        // 取出 LocalStorage 中的数据
        let storage = window.localStorage;
        const storage_str_data = storage.getItem("my_blog_data");
        let storage_json_data = JSON.parse(storage_str_data);
        // 若数据不存在，则创建空字典
        if (!storage_json_data) {
            storage_json_data = {}
        };
        // 检查当前文章是否已点赞。是则 status = true
        const status = check_status(storage_json_data, id);
        if (status) {
            layer.msg('已经点过赞了哟~');
            // 点过赞则立即退出函数
            return;
        } else {
            // 用 Jquery 找到点赞数量，并 +1
            $('span#likes_number').text(likes + 1).css('color', '#dc3545');
        }
        // 用 ajax 向后端发送 post 请求
        $.post(
            url,
            // post 只是为了做 csrf 校验，因此数据为空
            {},
            function(result) {
                if (result === 'success') {
                    // 尝试修改点赞数据
                    try {
                        storage_json_data[id] = true;
                    } catch (e) {
                        window.localStorage.clear();
                    };
                    // 将字典转换为字符串，以便存储到 LocalStorage
                    const d = JSON.stringify(storage_json_data);
                    // 尝试存储点赞数据到 LocalStorage
                    try {
                        storage.setItem("my_blog_data", d);
                    } catch (e) {
                        // code 22 错误表示 LocalStorage 空间满了
                        if (e.code === 22) {
                            window.localStorage.clear();
                            storage.setItem("my_blog_data", d);
                        }
                    };
                } else {
                    layer.msg("与服务器通信失败..过一会儿再试试呗~");
                }

            }
        );
    };

    // 辅助点赞主函数，验证点赞状态
    function check_status(data, id) {
        // 尝试查询点赞状态
        try {
            if (id in data && data[id]) {
                return true;
            } else {
                return false;
            }
        } catch (e) {
            window.localStorage.clear();
            return false;
        };
    };

</script>

{% endblock script %}



